<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactTodo\Action\Workbench;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactTodo\Contract\ContactTodoContract;

/**
 * 添加待办.
 *
 * Class Store
 * @Controller
 */
class Show extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkContactContract
     */
    protected $workContactService;

    /**
     * @Inject
     * @var ContactTodoContract
     */
    protected $contactTodoService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployee;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/contactTodo/show", methods="GET")
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }

        // 接收参数
        $params = [
            'todoId' => (int) $this->request->input('todoId'),
        ];
        // 校验参数
        $this->validated($params);
        $params['corpId'] = $user['corpId'];
        $params['employeeId'] = $user['id'];

        $info = $this->contactTodoService->getContactTodoById($params['todoId']);
        $info['repeat'] = isset($info['repeat']) ? Json::decode($info['repeat']) : [];
        $info['endRepeat'] = isset($info['endRepeat']) ? Json::decode($info['endRepeat']) : [];
        $contact = $this->workContactService->getWorkContactById($info['contactId'], ['id', 'name', 'avatar']);
        $contact['avatar'] = file_full_url($contact['avatar']);
        $info['contactInfo'] = $contact;
        return $info;
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'todoId' => 'required|integer|min:1|bail',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'todoId.required' => '任务id必传',
        ];
    }
}
